<?PHP
//print_r($_GET);

require_once('../../../../../wp-load.php');
require_once('../../../../../wp-admin/includes/admin.php');
require_once(ABSPATH . WPINC . '/registration.php');
require_once(ABSPATH . WPINC . '/ms-functions.php');

try
{
	// bring user id
	$token= $_GET['access_token'];
	$url = "https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=" . $token;

	$data = json_decode(@file_get_contents($url));
	//$data= null;
	if( !isset($data->id) )
		throw new Exception('can not find the url specified');
		
	$username = $data->id;
	$shouldSignIn= true;

	if ( !username_exists( $username ) )
	{
		//echo "Username Not In Use! Creating a new alphaneumeric one.<br/>";
		$username='s'.$username;
		$random_password ='123457890';
		$user_email=$username.'@example.com';
		//$user_id = wp_create_user( $username, $random_password, $user_email );
		
		$role = 'contributor';
		$user_id=wp_insert_user( 
			array ('user_login' => $username, 'user_pass'=>$random_password, 'role' => $role, 'user_email'=>$user_email) 
		) ;
		//print_r($user_id);exit();
		//if( isset($user_id['errors']))
			//echo "error in creation";
	}
	
	if( $shouldSignIn)
	{
		//echo "signing in as: $username";
		$creds = array();
		$creds['user_login'] = $username;
		$creds['user_password'] ='123457890';
		$creds['remember'] = true;
		//even if a user change password, it should be updated here
		$ID= get_user_id_from_string($username);
		$creds['ID'] = $ID;
		//echo " : "; print_r( $ID);die; //(int) $userdata['ID']
		wp_update_user( $creds ) ;
		$user = wp_signon( $creds, false );
		
		//print_r($user); die;
		//global $current_user;
		//echo get_currentuserinfo();
		//header("Location: ".get_bloginfo("wpurl")."/wp-admin/profile.php?reauth=0");
		$completePath="";
		if( isset($_SERVER['HTTP_REFERER']) && !stristr($_SERVER['HTTP_REFERER'], 'localhost') )
		{
			$url= parse_url($_SERVER['HTTP_REFERER']);
			$completePath= $url['path']. "?". $url['query'];
			//echo $completePath; die;
		}
		// user level != author
		else if( current_user_can('publish_posts') == false)
			$completePath = "/wp-admin/admin.php?page=myan-sub-message-to-user&error=". urlencode("Your initial post has to be approved by me.");
		else
			$completePath = "/wp-admin/profile.php?reauth=0";
			
		//header("Location: ".get_bloginfo("url").$completePath);
		$url = array();
		$url['nextDestination']= get_bloginfo("url").$completePath;
		header('Content-type: application/json');
		echo json_encode($url);
		//echo '"goToUrl" get_bloginfo("url").$completePath;
	}
}catch(Exception $e)
{	
	//header("location: ". get_bloginfo("url"));
	header('HTTP/1.0 404 Not Found.');
	header('Reason: '. $e->getMessage());
	
	echo $e->getMessage();
}
function arrayToObject($d) {
	if (is_array($d)) {
		/*
		* Return array converted to object
		* Using __FUNCTION__ (Magic constant)
		* for recursive call
		*/
		return (object) array_map(__FUNCTION__, $d);
	}
	else {
		// Return object
		return $d;
	}
}

?>